package bussiness

import (
	mysqlDb "DouBan/db/mysql"
	"DouBan/db/redis"
	"DouBan/model"
	"DouBan/utils"
	"context"
	"errors"
	"fmt"
	"github.com/afocus/captcha"
	"time"
)

func UserCaptcha() ([]byte, string, error) {
	content, answer := utils.GenerateCaptcha(4, captcha.ALL)
	uuid := utils.GenerateUuid()
	if err := redis.MasterClient().SetEX(context.Background(), fmt.Sprintf("%s_captcha", uuid), answer, time.Minute).Err(); err != nil {
		return nil, "", err
	}
	return content, uuid, nil
}

func UserRegister(infoClaim *model.InfoClaim, userRegisterRequest UserRegisterRequest) (string, error) {
	userCaptcha := userRegisterRequest.Captcha
	answer, err := redis.MasterClient().Get(context.Background(), fmt.Sprintf("%s_captcha", infoClaim.Uuid)).Result()
	if err != nil {
		return "验证码已过期", err
	}
	if answer == userCaptcha {
		user := model.User{
			//Uid:      utils.GenerateUuid(),
			UserName: userRegisterRequest.UserName,
			PassWord: utils.GetMd5(userRegisterRequest.PassWord),
		}
		if err = mysqlDb.MasterDb().Create(&user).Error; err != nil {
			return "创建用户失败", err
		} else {
			return "注册成功", nil
		}
	} else {
		return "验证码错误", errors.New("验证码错误")
	}
}

func UserLogin(infoClaim *model.InfoClaim, userLoginRequest UserLoginRequest) (string, error) {
	userCaptcha := userLoginRequest.Captcha
	answer, err := redis.MasterClient().Get(context.Background(), fmt.Sprintf("%s_captcha", infoClaim.Uuid)).Result()
	if err != nil {
		return "验证码已过期", err
	}
	if answer == userCaptcha {
		user := model.User{}
		mysqlDb.MasterDb().Where(&model.User{UserName: userLoginRequest.UserName}).Limit(1).First(&user)
		if user.PassWord != userLoginRequest.PassWord {
			return "用户鉴权失败", err
		}
		infoClaim.UserId = user.Id
		return "登录成功", nil
	} else {
		return "验证码错误", err
	}
}
